package com.ib.review.service.impl;

import com.ib.review.base.exception.ServiceException;
import com.ib.review.base.response.FileResponse;
import com.ib.review.base.response.StatusCode;
import com.ib.review.base.utils.UploadFiles;
import com.ib.review.constant.CommonConstant;
import com.ib.review.pojo.dto.ExternalParam;
import com.ib.review.service.ExternalService;
import com.ib.review.util.RedisUtil;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class ExternalServiceImpl implements ExternalService {

    private RedisUtil redisUtil;
    @Autowired
    private void setRedisUtil(RedisUtil redisUtil){
        this.redisUtil = redisUtil;
    }

    @Resource
    private UploadFiles uploadFiles;

    RestTemplate restTemplate = new RestTemplate();

    @Value("${file-system.download}")
    private String download;
    @Value("${file-system.external-create}")
    private String externalCreate;
    @Value("${file-system.username}")
    private String username;

    public String upload(MultipartFile file, ExternalParam param) {
        String fileName = file.getOriginalFilename();
        if(fileName == null || fileName.isEmpty()){
            throw new ServiceException(StatusCode.FILENAME_ISNULL);
        }
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 获取登录文件系统令牌
        String onlineID = getLoginToken();
        // 校验是否创建文件夹
        if(!"1".equals(redisUtil.get(CommonConstant.FILE_SYSTEM_EXTERNAL))){
            uploadFiles.createDirectory(externalCreate,onlineID);
            redisUtil.set(CommonConstant.FILE_SYSTEM_EXTERNAL,"1");
        }
        String filePath = "/" + username + externalCreate + "/" + param.getFileName() + suffix;
        try {
            uploadFiles.uploadWithRestTemplate(file,filePath,onlineID);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return filePath;
    }

    public byte[] download(String filePath) {
        // 获取登录文件系统令牌
        String onlineID = getLoginToken();
        String url = download + "?path=" + filePath;

        HttpHeaders headers = new HttpHeaders();
        headers.add("userOnlineID", onlineID);
        headers.add(HttpHeaders.ACCEPT, MediaType.ALL_VALUE);

        HttpEntity<String> entity = new HttpEntity<>(headers);

        // 发送请求
        ResponseEntity<byte[]> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                entity,
                byte[].class
        );
        return response.getBody();
    }

    private String getLoginToken(){
        // 获取登录文件系统令牌
        String onlineID = redisUtil.get(CommonConstant.FILE_SYSTEM_LOGIN);
        if(StringUtils.isEmpty(onlineID)){
            FileResponse fileResponse = uploadFiles.getOnlineID();
            onlineID = fileResponse.getUserOnlineID();
            Integer tokenExpireTime = fileResponse.getTokenExpireTime();
            redisUtil.setex(CommonConstant.FILE_SYSTEM_LOGIN, onlineID, tokenExpireTime-20, TimeUnit.SECONDS);
        }
        return onlineID;
    }
}
